<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getSysAuthorityRoute, addSysAuthorityRoute, delSysAuthorityRoute } from "@/api/sysUser"
import { getAllRole } from "@/api/sysRole"

import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { formatDate } from "@/utils/index"
import { getTablecvg, upLoadFile } from "@/api/table/index"
import upfilebox from "@/components/table/upfile.vue"

defineOptions({
  // 命名当前组件
  name: "routerclass"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const roleList = ref<any>([]) // 角色列表

getAllRole({}).then((res) => {
  roleList.value = res.data
})

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  image: "",
  userName: "",
  password: "",
  roleId: "",
  gender: 1,
  status: 1,
  groupName: "",
  department: "",
  companies: "",
  numeratorCompanies: "",
  project: "",
  teams: ""
})
const formRules: FormRules = reactive({
  // name: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  // path: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        addSysAuthorityRoute(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        addSysAuthorityRoute({
          id: currentUpdateId.value,
          ...formData
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
// 重置数据
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.name = ""
  formData.image = ""
  formData.userName = ""
  formData.password = ""
  formData.status = 1
  formData.gender = 1
  formData.roleId = ""

  formData.groupName = ""
  formData.department = ""
  formData.companies = ""
  formData.numeratorCompanies = ""
  formData.project = ""
  formData.teams = ""
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`正在删除：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delSysAuthorityRoute({
      integers: row.id
    }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  currentUpdateId.value = row.id
  formData.name = row.name
  formData.image = row.image
  formData.userName = row.userName
  // formData.password = row.password
  formData.status = row.status
  formData.roleId = row.roleId

  formData.groupName = row.groupName
  formData.department = row.department
  formData.companies = row.companies
  formData.numeratorCompanies = row.numeratorCompanies
  formData.project = row.project
  formData.teams = row.teams
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<any[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  id: ""
})
// 获取列表数据
const getTableData = () => {
  loading.value = true
  getSysAuthorityRoute({
    page: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    scoreState: 2,
    name: searchData.name || undefined,
    id: searchData.id || undefined
  })
    .then((res) => {
      paginationData.total = res.data.total
      console.log(res)

      tableData.value = res.data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

const handleDowcvg = () => {
  let params = {
    isCheck: true
  }
  // params["id"] = TableSelect_change.value.map((it) => it.id).join(",")
  getTablecvg(params, "/sysUser/downloadTemplate").then((res: any) => {
    const blobs = new Blob([res], { type: "application/vnd.ms-excel" })
    // console.log(blobs);
    const url = window.URL.createObjectURL(blobs)
    const a = document.createElement("a")
    a.href = url
    a.download = `人员导入模版.xlsx`
    a.click()
    //释放
    window.URL.revokeObjectURL(url)
  })
}

const fileChange = (e: any) => {
  const file = e.target.files[0]
  fileUpdate(file)
}
/** 上传文件 导入数据 */
const uploadFileFn = () => {
  // dialogVisibleFile.value = true
  let inputs = document.createElement("input")
  inputs.type = "file"
  // inputs.accept =
  inputs.addEventListener("change", fileChange)
  inputs.click()
}
// 调用上传接口
const fileUpdate = (file: any) => {
  console.log(file, "--upLoadFile-")

  //文件上传
  upLoadFile({ file }, "/sysUser/importData").then((res: any) => {
    console.log("---", res)
    if (res.code == 200) {
      ElMessage.success("导入成功!")
      resetSearch()
      return
    }
  })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="用户名">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="id" label="用户id">
          <el-input v-model="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button> -->
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-button type="primary" :icon="Download" @click="handleDowcvg">下载模版</el-button> -->
          <!-- <el-button type="primary" @click="uploadFileFn"> 导入数据 </el-button> -->
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="handleDowcvg" />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <!-- <el-table-column prop="id" label="id" align="center" /> -->
          <el-table-column prop="name" label="用户名" align="center" />
          <el-table-column prop="userName" label="用户登陆账号" align="center" />
          <el-table-column prop="image" label="头像" align="center">
            <template #default="scope">
              <img :src="scope.row.image" class="tableuserimg" />
            </template>
          </el-table-column>
          <el-table-column prop="roleId" label="职责ID" align="center" />
          <el-table-column prop="roleName" label="职责" align="center" />
          <el-table-column prop="gender" label="用户性别" align="center">
            <template #default="scope">
              <div>{{ { "1": "男", "2": "女", "3": "未知" }[scope.row.gender] }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="状态分数" align="center">
            <template #default="scope">
              <div>{{ scope.row.score }}分</div>
            </template>
          </el-table-column>
          <el-table-column prop="scoreState" label="分数状态" align="center">
            <template #default="scope">
              <div>{{ { "1": "正常", "2": "异常", "3": "未知" }[scope.row.scoreState] }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="groupName" label="集团" align="center" />
          <el-table-column prop="department" label="部门" align="center" />
          <el-table-column prop="companies" label="公司" align="center" />
          <el-table-column prop="numeratorCompanies" label="分子公司" align="center" />
          <el-table-column prop="project" label="项目" align="center" />
          <el-table-column prop="teams" label="班组" align="center" />
          <el-table-column prop="status" label="用户状态" align="center">
            <template #default="scope">
              <!-- <div>{{ scope.row.status=='0'?'关闭':'启用'  }}</div> -->
              <el-button type="success" v-if="scope.row.status == '1'">启用</el-button>
              <el-button type="info" v-else>关闭</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              <div>{{ formatDate(scope.row.createTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <!-- <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button> -->
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="用户名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="image" label="头像">
          <!-- <el-input v-model="formData.image" placeholder="请输入" /> -->
          <upfilebox v-model="formData.image"></upfilebox>
        </el-form-item>
        <el-form-item prop="userName" label="用户登陆账号">
          <el-input v-model="formData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="password" label="登陆密码">
          <el-input v-model="formData.password" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="roleId" label="角色ID">
          <el-select v-model="formData.roleId" class="m-2" placeholder="Select" size="large">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="用户状态">
          <el-radio-group v-model="formData.status" class="ml-4">
            <el-radio :label="0" size="large">关闭</el-radio>
            <el-radio :label="1" size="large">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="gender" label="用户性别">
          <el-radio-group v-model="formData.gender" class="ml-4">
            <el-radio :label="1" size="large">男</el-radio>
            <el-radio :label="2" size="large">女</el-radio>
            <el-radio :label="3" size="large">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="userName" label="集团">
          <el-input v-model="formData.groupName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="department" label="部门">
          <el-input v-model="formData.department" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="companies" label="公司">
          <el-input v-model="formData.companies" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="numeratorCompanies" label="分子公司">
          <el-input v-model="formData.numeratorCompanies" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="project" label="项目">
          <el-input v-model="formData.project" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="teams" label="班组">
          <el-input v-model="formData.teams" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.tableuserimg {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
